package com.modules.project.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.modules.common.enums.PublicEnum;
import com.modules.common.web.BaseController;
import com.modules.common.web.Result;
import com.modules.project.entity.BaseMessage;
import com.modules.project.service.MailManageService;
import com.modules.project.service.MailSendService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description: 邮件api
 * @author lc
 */
@Slf4j
@RestController
@RequestMapping("/api/mail")
@Api(tags="邮件api请求入口")
public class MailController extends BaseController {
	
	@Autowired
	private MailManageService manageService;
	@Autowired
	private MailSendService sendService;

	 /**
	  * @Description: 通用发送邮件接口
	  * @author lc
	  */
	 @ApiOperation(value= "发送邮件", notes= "发送邮件接口")
	 @RequestMapping(value = "/general/send", method = RequestMethod.POST, produces = "application/json")
	 @ResponseBody
	 public Result generalSend(HttpServletRequest request, @RequestBody BaseMessage baseMessage, BindingResult result){
		 log.info("[通用请求]开始请求发送邮件, 业务原始请求参数为: {}", JSONObject.toJSONString(baseMessage));
		 Assert.notNull(baseMessage.getTo(), "邮件缺少接收者信息");
		 Assert.notNull(baseMessage.getSubject(), "邮件缺少主题信息");
		 Assert.notNull(baseMessage.getAttachFlag(), "邮件缺少标识信息");
		 if(PublicEnum.Y.getCode().equals(baseMessage.getAttachFlag())){
			 Assert.notNull(baseMessage.getAttachType(), "邮件缺少附件类型信息");
			 Assert.notNull(baseMessage.getAttachName(), "邮件缺少附件名称信息");
			 Assert.notNull(baseMessage.getAttachContent(), "邮件缺少附件内容信息");
		 }
		 return success(manageService.preposition(baseMessage));
	 }
	 
    /**
     * @Description: 发送邮件是否连通
     * @author lc
     * @throws Exception 
     */
	@ApiOperation(value= "检查邮件服务器连通性", notes= "发送邮件检查是否连通邮件服务器")
	@RequestMapping(value = "/sendEmailReq", method = RequestMethod.POST, produces = "application/json")
	@ResponseBody
	public Result sendEmailReq(@RequestBody BaseMessage email) {
		log.info("发送开始-邮件信息：{}", JSONArray.toJSON(email));
		return success(sendService.sendMail(email));
	}
}
